const Fabric_Client = require('fabric-client');
const path = require('path');
const fs = require("fs");
const fabric_client = new Fabric_Client();
const config = require('../config');

module.exports = {

    storePath: function (msp) {

        let store_path = path.resolve(__dirname, `../../hfc-key-store/${msp}`);

        return new Promise(function (resolve, reject) {
            fs.exists(store_path, function (exists) {
                if (!exists) {
                    try {
                        fs.mkdir(store_path, function () {
                            resolve(store_path);
                        })
                    } catch (e) {
                        reject(e)
                    }

                } else {
                    resolve(store_path);
                }
            })
        });
    },

    getObj: function (type, fcn, args) {
        //获取order配置
        const chain_config = config.load("chain");
        const user_config = config.load("user");

        let obj = {};
        //channel
        obj.channel = "mychannel2";
        obj.chaincode = type;
        //msp
        obj.msp = "Org3MSP";
        //peer
        obj.p_adr_core = chain_config.peer.core_address;
        obj.p_adr_event = chain_config.peer.event_address;
        obj.peer = chain_config.peer.name;
        let root_path = path.resolve(__dirname, `../../`);//  app/
        obj.p_tls = fs.readFileSync(root_path + "/" + chain_config.peer.tls);
        //func
        obj.fcn = fcn;
        obj.args = args;
        //order
        obj.order_adr_core = chain_config.order.core_address;
        obj.order = chain_config.order.name;
        obj.order_tls = fs.readFileSync(root_path + "/" + chain_config.order.tls);
        //ca

        obj.ca_name = user_config.name;
        obj.ca_password = user_config.password;

        obj.ca_address = chain_config.ca.address;

        return obj
    },

    getEventObj: function (type) {
        //获取order配置
        const chain_config = config.load("chain");
        const user_config = config.load("user");

        let obj = {};
        //channel
        obj.channel = "mychannel2";
        obj.chaincode = type;
        //msp
        obj.msp = "Org3MSP";
        //peer
        obj.p_adr_core = chain_config.peer.core_address;
        obj.p_adr_event = chain_config.peer.event_address;
        obj.peer = chain_config.peer.name;
        let root_path = path.resolve(__dirname, `../../`);//  app/
        obj.p_tls = fs.readFileSync(root_path + "/" + chain_config.peer.tls);
        //order
        obj.order_adr_core = chain_config.order.core_address;
        obj.order = chain_config.order.name;
        obj.order_tls = fs.readFileSync(root_path + "/" + chain_config.order.tls);
        //ca

        obj.ca_name = user_config.name;
        obj.ca_password = user_config.password;

        obj.ca_address = chain_config.ca.address;
        return obj
    }
}